package com.layton.work_queue;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer_WorkQueue2 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置连接参数
        factory.setHost("127.0.0.1");//默认值为localhost
        factory.setPort(5672);//默认值为5672
        factory.setVirtualHost("/layton");//虚拟机默认为/
        factory.setUsername("layton");//guest
        factory.setPassword("layton");//guest
        //3.获取对应连接connection
        Connection connection = factory.newConnection();
        //4.创建channel
        Channel channel = connection.createChannel();
        //5.创建队列queue,名字有则创建,没有则不会创建
        channel.queueDeclare("work_queue", true, false, false, null);
        //6.收消息
        Consumer consumer = new DefaultConsumer(channel) {
            //回调方法,当收到消息后会自动执行该方法
            /**
             * @param consumerTag 标识
             * @param envelope 获取一些信息,交换机,路由key
             * @param properties 配置信息
             * @param body 真实的数据
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumerTag = " + consumerTag);
                System.out.println("envelopeExchange = " + envelope.getExchange());
                System.out.println("envelopeRoutingKey = " + envelope.getRoutingKey());
                System.out.println("properties = " + properties);
                System.out.println("body = " + new String(body));
            }
        };
        channel.basicConsume("work_queue",true,consumer);
        //7.不要释放资源
    }
}

/*
    String queue, boolean autoAck, Consumer callback
    参数:
        queue 队列名
        autoAck 是否自动确认,和mq说一声我收到了
        callback 回调对象
 */